<?php

/**
 * 用户令牌服务
 * @author UCToo <contact@uctoo.com>
 * Date: 2018/1/9
 * Time: 19:15
 */

namespace catchAdmin\wechatopen\service;

use catchAdmin\wechatopen\model\WechatopenMiniappUsers;
use think\facade\Log;

defined('TOKEN_PATH') or define('TOKEN_PATH', runtime_path('token') );

class TokenService
{
    public $userId;
    public $openId;
    public $userInfo;
    protected $available = false;

    protected static $options = [
        // 缓存类型为File
        'type' => 'File',
        // 缓存有效期与前端登录态一致最多3天有效
        'expire' => 259200,
        // 指定缓存目录
        'path' => TOKEN_PATH,
    ];

    public static function check($token)
    {
        $user = cache($token);   //用token从缓存获取用户帐号，user中包含session_key、token、access_token_overtime、appid、openid、unionid信息，todo：弃用本地缓存，采用云端redis等可持久化缓存，避免容器化影响

        if ($user!= null) {
            if( time() < ($user['access_token_overtime']-3600)){                //token在有效期内
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     *  缓存用户自定义登录态
     */
    public static function cacheSession($oldToken,$data)
    {
        cache($oldToken,null,self::$options);
        cache($data['token'],$data,self::$options);
    }
}